# coding=utf-8
import logging
import json

import arrow
from django.template import Context, Template

from common.utils.tz import now_ts
from common.cache import redis_cache

_LOGGER = logging.getLogger('bigbang')


def _fill_text(text, params):
    """
    text: u'恭喜大白菜{{ time }}前获得iphone6s'
    params: {
        'ts': 1450789931
    }
    """
    template = Template(text)
    if params.get('ts'):
        params['time'] = arrow.get(int(params['ts'])).humanize(locale="zh_cn")
    context = Context(params)
    return template.render(context)


def spread(user_name, price):
    _LOGGER.info('start spread scrolling')
    _SCROLLING_LIMIT = 20
    ts = now_ts()
    scrolling_dict = {
        'text': u'恭喜【%s***】中奖<font color="red">%s</font>元' % (user_name[0], str(price)),
        'params': {
            'ts': ts
        }
    }
    redis_cache.submit_scrolling(json.dumps(scrolling_dict, ensure_ascii=False), ts)
    if redis_cache.get_scrolling_count() > _SCROLLING_LIMIT:
        redis_cache.trim_scrolling()
